package com.example.teamtribe.main.club.posting;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.teamtribe.R;
import com.example.teamtribe.common.userinfo.UserInfoActivity;
import com.example.teamtribe.database.Posting;
import com.example.teamtribe.database.User;
import com.example.teamtribe.utils.Utility;

import java.util.List;

public class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.ViewHolder> {

    private Context context;
    private List<Posting> comments;

    public CommentAdapter(List<Posting> comments) {
        this.comments = comments;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        context = parent.getContext();
        View view = LayoutInflater.from(context).inflate(R.layout.item_comment, parent, false);
        final ViewHolder holder = new ViewHolder(view);
        view.findViewById(R.id.iv_head).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition() - 1;
                User user = Utility.getT(comments.get(position).getUserId(), User.class);
                if (user != null) {
                    Intent intent = new Intent(context, UserInfoActivity.class);
                    intent.putExtra("user", user);
                    context.startActivity(intent);
                }
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Posting posting = comments.get(position);
        holder.tvInfo.setText(posting.getCreateTime());
        holder.tvContent.setText(posting.getContent());
        User user = Utility.getT(posting.getUserId(), User.class);
        if (user != null) {
            holder.tvNickname.setText(user.getNickname());
            Glide.with(context).load(Utility.getUri(user.getPortrait())).into(holder.ivHead);
        }
    }

    @Override
    public int getItemCount() {
        return comments.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        ImageView ivHead;
        TextView tvNickname;
        TextView tvInfo;
        TextView tvContent;

        public ViewHolder(View itemView) {
            super(itemView);
            ivHead = itemView.findViewById(R.id.iv_head);
            tvNickname = itemView.findViewById(R.id.tv_nickname);
            tvInfo = itemView.findViewById(R.id.tv_info);
            tvContent = itemView.findViewById(R.id.tv_content);
        }
    }
}
